package com.basiclib

import android.app.Application
import android.content.Context
import javax.inject.Inject
import javax.inject.Named

/**
 * ================================================
 * AppDelegate 可以代理 Application 的生命周期,在对应的生命周期,执行对应的逻辑,因为 Java 只能单继承
 * 所以当遇到某些三方库需要继承于它的 Application 的时候,就只有自定义 Application 并继承于三方库的 Application
 * 这时就不用再继承 BaseApplication,只用在自定义Application中对应的生命周期调用AppDelegate对应的方法
 * (Application一定要实现APP接口),框架就能照常运行
 *
 * @see BaseApplication
 *
 * @see [AppDelegate wiki 官方文档](https://github.com/JessYanCoding/MVPArms/wiki.3.12)
 * Created by JessYan on 24/04/2017 09:44
 * [Contact me](mailto:jess.yan.effort@gmail.com)
 * [Follow me](https://github.com/JessYanCoding)
 * ================================================
 */
class AppDelegate(context: Context) {
    private var mApplication: Application? = null
    @Inject
    @Named("ActivityLifecycle")
    protected var mActivityLifecycle: Application.ActivityLifecycleCallbacks? = null
    @Inject
    @Named("ActivityLifecycleForRxLifecycle")
    protected var mActivityLifecycleForRxLifecycle: Application.ActivityLifecycleCallbacks? = null

    fun attachBaseContext(base: Context) {
    }

    fun onCreate(application: Application) {
        this.mApplication = application

        //注册框架内部已实现的 Activity 生命周期逻辑
        mApplication!!.registerActivityLifecycleCallbacks(mActivityLifecycle)

        //注册框架内部已实现的 RxLifecycle 逻辑
        mApplication!!.registerActivityLifecycleCallbacks(mActivityLifecycleForRxLifecycle)
    }


    fun onTerminate(application: Application) {
        if (mActivityLifecycle != null) {
            mApplication!!.unregisterActivityLifecycleCallbacks(mActivityLifecycle)
        }
        if (mActivityLifecycleForRxLifecycle != null) {
            mApplication!!.unregisterActivityLifecycleCallbacks(mActivityLifecycleForRxLifecycle)
        }
        this.mActivityLifecycle = null
        this.mActivityLifecycleForRxLifecycle = null

        this.mApplication = null
    }

}

